package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.MenuMapper;
import com.cmii.sjw.department.control.jsc.mapper.RoleMapper;
import com.cmii.sjw.department.control.jsc.mapper.RoleMenuMapper;
import com.cmii.sjw.department.control.jsc.model.entity.Menu;
import com.cmii.sjw.department.control.jsc.model.entity.Role;
import com.cmii.sjw.department.control.jsc.model.entity.RoleMenu;
import com.cmii.sjw.department.control.jsc.service.RoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jfh
 * @Date 2025-04-08 周二 11:32
 * @Version 1.0
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Role> getRolesByIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<Role> roleQueryWrapper = new LambdaQueryWrapper<>();
        roleQueryWrapper.in(Role::getId, roleIds);
        return roleMapper.selectList(roleQueryWrapper);
    }

    @Override
    public List<Menu> getMenusByRoleIds(List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Collections.emptyList();
        }

        // 1. 查询角色菜单关联关系
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RoleMenu::getRoleId, roleIds);
        List<RoleMenu> roleMenus = this.list(wrapper);

        if (CollectionUtils.isEmpty(roleMenus)) {
            return Collections.emptyList();
        }

        // 2. 获取菜单ID列表
        List<Long> menuIds = roleMenus.stream()
                .map(RoleMenu::getMenuId)
                .distinct()
                .collect(Collectors.toList());

        // 3. 查询菜单详情
        LambdaQueryWrapper<Menu> menuQueryWrapper = new LambdaQueryWrapper<>();
        menuQueryWrapper.in(Menu::getId, menuIds);
        return menuMapper.selectList(menuQueryWrapper);
    }
}
